# Title: 业务方通知文本
# Params: ip_list|multi_str|10.126.0.143

import python_calamine


def xlsx_to_dict(file: str, sheet_index=0) -> list[dict]:
    with open(file, 'rb') as file:
        workbook = python_calamine.CalamineWorkbook.from_filelike(file)
        _rows = iter(workbook.get_sheet_by_index(sheet_index).to_python())
        headers = list(map(str, next(_rows)))
        _values = [dict(zip(headers, row)) for row in _rows]

    return _values


def server_filter(_data, _ip):
    for x in _data:
        if x['管理IP'] and x['IPMIIP']:
            if x['管理IP'].strip() == _ip or x['IPMIIP'].strip() == _ip:
                return x


def main():
    all_devs = xlsx_to_dict("./depository/台账/IT云贵池设备台账.xlsx", 0)
    _result = {}
    err = []
    output = []
    for _ip in ip_list.split():
        server_item = server_filter(all_devs, _ip)
        if not server_item:
            err.append(_ip)
            continue

        _data = [
            server_item.get("主机名称"),
            f'管理网：{server_item.get("管理IP")}',
            f'IPMI：{server_item.get("IPMIIP")}',
        ]
        business_ip = server_item.get("业务IP")
        if business_ip:
            _data.append(f'业务网：{business_ip}')

        if not _result.get(server_item['应用系统']):
            _result[server_item['应用系统']] = []

        _result[server_item['应用系统']].append(_data)
    num_index = 0
    for k, v in _result.items():
        output.append(f'{k}：')
        for n in v:
            num_index += 1
            n.insert(0, f'{num_index}、')
            output.append('  '.join(n))
    if err:
        output.append(f"\n\n以下IP未匹配到: \n {', '.join(err)}")

    return '\n'.join(output)
